package com.tuanzi.loan.business.service.schedule;

import com.tuanzi.loan.business.constants.push.LoanPushMessageSendTaskStatus;
import com.tuanzi.loan.business.entity.push.LoanPushMessageSendTask;
import com.tuanzi.loan.business.service.push.LoanPushMessageSendTaskService;
import com.tuanzi.loan.core.aspect.Debug;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

/**
 * @Author: chenweijun
 * @Date: 2018/12/21 15:39
 * @Description:推送消息定时任务
 */
@Debug
@Slf4j
@Service
@Transactional
public class PushMessageScheduler {

    @Autowired
    private LoanPushMessageSendTaskService loanPushMessageSendTaskService;

    @Scheduled(cron = "${cron.send-push-message}")
    public void sendPushMessage(){

        if(loanPushMessageSendTaskService.countByStatus(LoanPushMessageSendTaskStatus.SENDING) > 0){
            return;
        }

        LoanPushMessageSendTask sendTask = loanPushMessageSendTaskService.findTopByStatusAndSendTimeBefore(LoanPushMessageSendTaskStatus.READY_SEND, new Date());
        if(Objects.isNull(sendTask)){
            return;
        }
        loanPushMessageSendTaskService.updateStatusWithoutTransactional(sendTask, LoanPushMessageSendTaskStatus.SENDING);
        loanPushMessageSendTaskService.sendPushMessage(sendTask);
    }
}
